package com.zzyl.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class wechatServiceImpl implements WechatService {
    /**
     * 获取用户openid
     */
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
    /**
     * 获取token
     */
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    /**
     * 获取手机号                            //https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=
     */
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${zzyl.framework.wechat.appId}")
    private  String appId;
    @Value("${zzyl.framework.wechat.appSecret}")
    private  String appSecret;


    @Override
    public String getOpenId(String code) {
        Map<String, Object> map = getMap();
        map.put("js_code", code);
        String s = HttpUtil.get(REQUEST_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        if(ObjectUtil.isNotEmpty(jsonObject.get("errcode"))){
            throw new RuntimeException(jsonObject.get("errmsg").toString());
        }
        String openId = (String) jsonObject.get("openid");
        return openId;
    }

    @Override
    public String getPhoneNumber(String code) {
        String token = getToken();
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        String phoneNumber = HttpUtil.post(PHONE_URL + token,JSONUtil.toJsonStr(map));
        JSONObject jsonObject = JSONUtil.parseObj(phoneNumber);
        System.out.println(jsonObject.toString());
        if( (Integer) jsonObject.get("errcode") != 0){
            throw new RuntimeException(jsonObject.get("errmsg").toString());
        }
        JSONObject object = (JSONObject) jsonObject.get("phone_info");
        String phoneNum = (String) object.get("phoneNumber");
        return phoneNum;
    }

    public  String getToken(){
        Map<String, Object> map = getMap();
        String tokenUrl = HttpUtil.get(TOKEN_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(tokenUrl);
        String accessToken = (String) jsonObject.get("access_token");
        return accessToken;
    }


    /**
     * 抽取的公共map方法
     * @return
     */
    public  Map<String, Object> getMap() {
        Map<String,Object> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", appSecret);
        return map;
    }
}
